﻿namespace JoinBox.WPF;

using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

// https://www.cnblogs.com/TianFang/p/3969430.html
public static class HostVisualHost
{
    /// <summary>
    /// 新建线程让WPF的UI执行
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="container">子控件</param>
    public static void CreateChildInNewThread<T>(ContentControl container) where T : UIElement, new()
    {
        HostVisual hostVisual = new();

        var content = new VisualHost(hostVisual);
        container.Content = content;

        var thread = new Thread(() => {
            var visualTarget = new VisualTarget(hostVisual);

            var control = new T();
            control.Arrange(new Rect(new Point(), content.RenderSize));

            visualTarget.RootVisual = control;
            Dispatcher.Run();
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();
    }
}
public class VisualHost : FrameworkElement
{
    readonly Visual _child;

    public VisualHost(Visual child)
    {
        _child = child ?? throw new ArgumentNullException(nameof(child));
        AddVisualChild(child);
    }

    protected override Visual? GetVisualChild(int index)
    {
        return (index == 0) ? _child : null;
    }

    protected override int VisualChildrenCount
    {
        get { return 1; }
    }
}